const client = require('@mctech/infra-cloud').getRpcClient()

async function _handleLicenseMode (config, service) {
  service.use(async (ctx, next) => {
    const orgId = ctx.extras.orgId || ctx.query.orgId

    let licenseMode = 'company'
    if (orgId) {
      const featurePacks = await client.get({
        path: `/orgs/${orgId}/feature-packs`,
        method: 'GET'
      }, {
        serviceId: 'permission-service'
      })
      const bimFeatureCodes = ['cq-highway', 'cq-railway', 'cq-municipal', 'cq-subway']
      if (featurePacks.some(pack => bimFeatureCodes.includes(pack.code))) {
        licenseMode = 'project'
      }
    }

    ctx.extras.licenseMode = licenseMode
    await next()
  })
}

module.exports = {
  _handleLicenseMode
}
